/*
class Solution {
public:
    string findLongestWord(string s, vector<string>& d) {       
        int maxlength=0;
        int index=0;
        bool matched=false;
        for (int it=0;it<d.size();it++)
        {
            if(isContained(s,d[it]))
            {
                if(d[it].size()>maxlength)
                {
                    maxlength=d[it].size();
                    index=it;
                }
                if(d[it].size()==maxlength)
                {
                    if(d[it]<d[index])
                    {
                        maxlength=d[it].size();
                        index=it;
                    }
                }
                matched=true;
            }
        }
        if(matched)
        {
            return d[index];
        }
        else
        {
            return "";
        }
    }
    
    bool isContained(string& father,string& son){
        int i=0;
        int j=0;
        while(i!=son.size())
        {
            while(j!=father.size())
            {
                if(son[i]==father[j])
                {
                    break;
                }
                j++;
            }
            if(j==father.size())
            {
                return false;
            }
            i++;
        }
        return true;
    }
};
*/
class Solution {
public:
    string findLongestWord(string s, vector<string>& d) {       
        string max_str="";
        for (int i=0;i<d.size();i++){
            if(isContained(s,d[i])){
                if(d[i].size()>max_str.size()||(d[i].size()==max_str.size()&&d[i]<max_str)){
                    max_str=d[i];
                }
            }
        }
        return max_str;
    }
    
    bool isContained(string& father,string& son){

        int j=0;
        for(int i=0;i<father.size()&&j<son.size();i++){
            if(son[j]==father[i]){
                j++;
            }
        }
        return j==son.size();
    }
};